import http from "@/api/login";
import { message } from "ant-design-vue";
import { auths } from "@/utils/auth";

export default {
  namespaced: true,
  state: {
    token: "",
    userInfo: {}, //用户信息
    authData: {} //权限数据
  },
  mutations: {
    setToken(state, value) {
      state.token = value;
    },
    saveUserInfo(state, value) {
      state.userInfo = value || {};
    },
    initalAuth(state, role) {
      state.authData = auths(role);
    },
    user_logout(state) {
      state.token = "";
      state.userInfo = {};
    }
  },
  actions: {
    saveUserInfo({ commit }, value) {
      return new Promise((resolve, reject) => {
        if (value.member && value.token) {
          commit("saveUserInfo", value.member);
          commit("setToken", value.token);
          resolve();
        } else {
          reject();
        }
      });
    },
    initalAuth({ commit }, role) {
      commit("initalAuth", role);
    },
    logout({ commit, dispatch }) {
      return http
        .logout()
        .then((res) => {
          if (res.retcode === 0) {
            commit("user_logout");
            dispatch("index_logout", {}, { root: true });
            message.success(res.data || "退出成功！");
          } else {
            message.info("退出失败！");
          }
        })
        .catch((err) => {
          message.error(err.msg);
        });
    }
  }
};
